package com.wwm.makerandroid.makerandroid.View.Fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lipiao.makerandroid.R;
import com.wwm.makerandroid.makerandroid.Bean.RespondBean.RecordBean;
import com.wwm.makerandroid.makerandroid.Bean.RespondBean.TempBean;
import com.wwm.makerandroid.makerandroid.Bean.RespondBean.TempBean2;
import com.wwm.makerandroid.makerandroid.Bean.ViewBean.ApplyBean;
import com.wwm.makerandroid.makerandroid.Bean.ViewBean.LeaveClearance;
import com.wwm.makerandroid.makerandroid.Utils.HttpUtil;
import com.wwm.makerandroid.makerandroid.View.Adapter.ApplyRecordAdapter;
import com.wwm.makerandroid.makerandroid.View.Adapter.MyImageView;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.List;
import java.util.Objects;


import butterknife.ButterKnife;
import butterknife.Unbinder;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class ShenheFragment extends Fragment {

    //    先把请假的审批
    static String userNumber;//账号
    Context mainActivity;
    String TAG = "ShenheFragment";
    View rootView;

    //碎片中使用butterknife略有不同
    private Unbinder unbinder;

    View applyView;
    //    Button detailBt;
//    打开请假申请按钮
    Button openLeaveApply;
    //    打开销假申请按钮
    Button openCleranceApply;


    //上一个未通过请假申请的数据
//    ApplyBean lastRefuseApply = new ApplyBean();
    RadioGroup vehicleRG;
    private List recordList;
    AlertDialog alertDialog;//模拟加载数据

    //    不需要
    //top article
    static ApplyRecordAdapter topArticleAdapter;
    //    static List<ArticleBean> mList = new ArrayList<>();
    RecyclerView mRecyclerView;
//    显示审批请假的对话框
    AlertDialog dialog;
//    输入拒绝原因对话框
    AlertDialog jujueReasonDialog;

    public ShenheFragment() {
        // Required empty public constructor
    }

    public static ShenheFragment newInstance(String userNumber) {
        ShenheFragment fragment = new ShenheFragment();
        Bundle bundle = new Bundle();
        bundle.putString("userNumber", userNumber);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mainActivity = getContext();
        rootView = inflater.inflate(R.layout.fragment_shenhe, container, false);
        mRecyclerView = rootView.findViewById(R.id.rv_shenhe_list);
        openLeaveApply = rootView.findViewById(R.id.bt_qingjia);
        openCleranceApply = rootView.findViewById(R.id.bt_xiaojia);
        openLeaveApply.setOnClickListener(mOnClickListener);
        openCleranceApply.setOnClickListener(mOnClickListener);
//        detailBt.setOnClickListener(mOnClickListener);
        //返回一个Unbinder值（进行解绑），注意这里的this不能使用getActivity()
        unbinder = ButterKnife.bind(this, rootView);
        assert getArguments() != null;//判空处理
        userNumber = getArguments().getString("userNumber");//获取账号
        Log.d(TAG, "onCreateView: userNumber " + userNumber);
        initData();
        //   初始化审核对话框
        initApplyDialogView();
        return rootView;
    }


    private void showApplyDialog(View view, Button button, String title) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        dialog= builder.create();
        try {
            ((ViewGroup)view.getParent()).removeView(view);
        }
        catch (Exception e){
            System.out.println(e);
        }
        dialog.setView(view);
        dialog.show();
        dialog.getWindow().setLayout(1420, 2500);
    }


    private void initData() {
        alertDialog = new AlertDialog.Builder(Objects.requireNonNull(getActivity()))
                .setMessage("获取请假记录中...")
                .setTitle("Maker——IoT").create();
        alertDialog.show();
        //LogUtil.d(TAG, "initData 验证是否重复加载碎片所需数据");

        getShenheRecoeds();
//        getShenheRecoeds(callBanner);
    }

    //    获得需审批的记录 列表
    void getShenheRecoeds() {
        //banner所需数据images titles
        Call<ResponseBody> callBanner = HttpUtil.getUserService().getWaitApproval(userNumber);
        //网络请求
        callBanner.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    String strBack = response.body().string();
                    //处理数据
                    JSONObject jsonObject = null;
                    jsonObject = new JSONObject(strBack);
                    Gson gson = new Gson();
                    RecordBean recordBean;

                    recordBean = gson.fromJson(jsonObject.toString(), RecordBean.class);
                    System.out.println(recordBean);
                    recordList = recordBean.getData();
                    initRecordView();

                    //获取完数据后UI操作
                    //主线程将alertDialog提示隐藏
                    Objects.requireNonNull(getActivity()).runOnUiThread(new Runnable() {
                        @Override
                        public void run() {

                            alertDialog.hide();
                        }
                    });
                } catch (JSONException e) {
                    System.out.println(e);
                    Log.d(TAG, "初始化项目数据成功");
                } catch (IOException e) {
                    System.out.println(e);
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.d(TAG, "初始化项目数据失败");
            }
        });
    }


    //初始化记录列表
    private void initRecordView() {
        //top rv
        mRecyclerView.setHasFixedSize(true);
        //平常的水平一个item布局的流
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);
        //设置预览信息
//初始化mList
//        initArticleBeanList();
//实例化MyAdapter并传入mList对象
        //这里原本是文章列表的构造器直接拿来复用了
        topArticleAdapter = new ApplyRecordAdapter(recordList);
//为RecyclerView对象mRecyclerView设置adapter
        mRecyclerView.setAdapter(topArticleAdapter);
    }


    // 处理审批请假的逻辑
    private View.OnClickListener mOnClickListener = new View.OnClickListener() {
        @SuppressLint("NonConstantResourceId")
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
//                处理请假申请
                case R.id.bt_qingjia:

//                    获得审核数据
                    getCurApplyBean(applyView);
                    showApplyDialog(applyView,new Button(mainActivity),"审核");
                    break;

//                通过申请
                case R.id.bt_submitApply:
                    Call<ResponseBody> call = HttpUtil.getUserService().shenhe(userNumber, curApplyBean.getId().toString(),
                            true, "批准", 1);
                    call.enqueue(new Callback<ResponseBody>() {
                        @Override
                        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                            Toast.makeText(mainActivity, "通过申请成功!", Toast.LENGTH_LONG).show();

                            dialog.dismiss();

                            getShenheRecoeds();
                        }

                        @Override
                        public void onFailure(Call<ResponseBody> call, Throwable t) {
                            Toast.makeText(mainActivity, "通过申请失败!", Toast.LENGTH_LONG).show();
                            dialog.dismiss();
                        }
                    });

                    break;

                case R.id.bt_cancel:
//               拒绝申请  拒绝申请会弹出对话框 要求填写拒绝原因  在点完填写原因对话框的确定按钮后 才发送请求 也就是在下一个case中处理
                    //打开对话框 //todo 抽象成的方法

                    AlertDialog.Builder builder = new AlertDialog.Builder(mainActivity);
                    jujueReasonDialog = builder.create();
                    View dialogView = View.inflate(mainActivity, R.layout.oneedit_dialog, null);
                    reasonTv = dialogView.findViewById(R.id.et_one_reason);
                    bt_sure = dialogView.findViewById(R.id.bt_sure);
                    bt_sure.setOnClickListener(mOnClickListener);
                    try {
                        ((ViewGroup)dialogView.getParent()).removeView(dialogView);
                    }
                    catch (Exception e){
                        System.out.println(e);
                    }
                    jujueReasonDialog.setView(dialogView);
                    jujueReasonDialog.show();
                    break;

                case R.id.bt_sure:
//                    带上拒绝理由
                    Call<ResponseBody> call2 = HttpUtil.getUserService().shenhe(userNumber, curApplyBean.getId().toString(),
                            false, reasonTv.getText().toString(), 1);
                    call2.enqueue(new Callback<ResponseBody>() {
                        @Override
                        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                            Toast.makeText(mainActivity, "拒绝申请成功!", Toast.LENGTH_LONG).show();
                            dialog.dismiss();
                            jujueReasonDialog.dismiss();
                            getShenheRecoeds();
//                            按理说 调用getShenheRecoeds在读取一次就能更新待审批列表了了 但是并没有， 所以审批完了 数据仍会在列表 需要重启应用才会更新
//                            不过不更新的话 点击审批按钮仍不会出错 因为会查数据库得到这个审批数据。
                        }

                        @Override
                        public void onFailure(Call<ResponseBody> call, Throwable t) {
                            Toast.makeText(mainActivity, "拒绝申请成功!", Toast.LENGTH_LONG).show();
                            dialog.dismiss();
                        }
                    });
                    break;


                case R.id.bt_xiaojia:
                    shenhexiaojia();
                    break;
//                    拒绝销假申请
                case R.id.jujue:
                    Call<ResponseBody> call3 = HttpUtil.getUserService().shenhe(userNumber, leaveClearance.getApplyId().toString(),
                            false, "核酸，健康码，行程码有误，请审查", 2);
                    call3.enqueue(new Callback<ResponseBody>() {
                        @Override
                        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                            Toast.makeText(mainActivity, "拒绝销假申请成功!", Toast.LENGTH_LONG).show();
                            dialog2.dismiss();
                            getShenheRecoeds();
//                            按理说 调用getShenheRecoeds在读取一次就能更新待审批列表了了 但是并没有， 所以审批完了 数据仍会在列表 需要重启应用才会更新
//                            不过不更新的话 点击审批按钮仍不会出错 因为会查数据库得到这个审批数据。
                        }

                        @Override
                        public void onFailure(Call<ResponseBody> call, Throwable t) {
                            Toast.makeText(mainActivity, "拒绝销假申请成功!", Toast.LENGTH_LONG).show();
                          dialog2.dismiss();
                            getShenheRecoeds();
                        }
                    });
                    break;
                case R.id.tongguo:
                    Call<ResponseBody> call4 = HttpUtil.getUserService().shenhe(userNumber, leaveClearance.getApplyId().toString(),
                            true, "批准", 2);
                    call4.enqueue(new Callback<ResponseBody>() {
                        @Override
                        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                            Toast.makeText(mainActivity, "通过销假申请成功!", Toast.LENGTH_LONG).show();
                            dialog2.dismiss();
                            getShenheRecoeds();
                        }

                        @Override
                        public void onFailure(Call<ResponseBody> call, Throwable t) {
                            Toast.makeText(mainActivity, "通过销假申请失败!", Toast.LENGTH_LONG).show();
                            dialog2.dismiss();
                        }
                    });


                    break;
                default:
                    break;
            }
        }
    };

    //打开对话框   还是复用的申请请假的页面 但是这里限制按钮,选择器,文字输入器等的输入  就只能显示读取到数据,而不能修改
//    然后把原来的提交按钮改为文字改为通过  再新增拒绝按钮  就实现对申请的审批了

    RadioGroup typeRG;
    Button startBt;
    Button endBt;
    EditText reasonText;
    Button destinationText;
    Spinner apprvoerSp;
    Button submitApplyBt;
    Button btRefuse;
    //    拒绝原因输入框
    TextView reasonTv;
    //拒绝原因确定按钮
    Button bt_sure;
    //    当前点击的申请;
    ApplyBean curApplyBean;


    public void initApplyDialogView() {
        applyView = View.inflate(getContext(), R.layout.apply_card_item, null);
//        typeRG = applyView.findViewById(R.id.user_fragment_banner);
        vehicleRG = applyView.findViewById(R.id.rgv1);
        typeRG = applyView.findViewById(R.id.rg);

        reasonText = applyView.findViewById(R.id.et_reason);
        destinationText = applyView.findViewById(R.id.text_diqu);

        startBt = applyView.findViewById(R.id.bt_start);
        endBt = applyView.findViewById(R.id.bt_end);
//        approverBt = rootView.findViewById(R.id.);
        btRefuse = applyView.findViewById(R.id.bt_cancel);


        submitApplyBt = applyView.findViewById(R.id.bt_submitApply);
        btRefuse = applyView.findViewById(R.id.bt_cancel);

        submitApplyBt.setText("批准");
        btRefuse.setText("拒绝");

        submitApplyBt.setOnClickListener(mOnClickListener);
        btRefuse.setOnClickListener(mOnClickListener);

        apprvoerSp = applyView.findViewById(R.id.spinner);
//        将对话框输入设置不可填写
        reasonText.setFocusableInTouchMode(false);
        destinationText.setFocusableInTouchMode(false);
//        将多选按钮也设置为不可选中
        for (int i = 0; i < vehicleRG.getChildCount(); i++) {
            vehicleRG.getChildAt(i).setEnabled(false);
        }
//        for (int i = 0; i < typeRG.getChildCount(); i++) {
//            typeRG.getChildAt(i).setEnabled(false);
//        }


    }


    private ApplyBean getCurApplyBean(View v) {
        //发送请求 获取当前点击的请假申请
        Call<ResponseBody> call = HttpUtil.getUserService().getLastwaitForApproverApply(userNumber);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    String strBack = response.body().string();
                    //处理数据
                    JSONObject jsonObject = null;
                    jsonObject = new JSONObject(strBack);
                    Gson gson = new Gson();

                    curApplyBean = gson.fromJson(jsonObject.toString(), TempBean.class).getData();
                    if (curApplyBean == null) {
                        return;
                    }
                    int type=curApplyBean.getType();
//                    todo 根据下标转换为id
                    typeRG.check(type-1);
                    startBt.setText(curApplyBean.getOutDate());
                    endBt.setText(curApplyBean.getExpectedReturnDate());
                    destinationText.setText(curApplyBean.getDestination());
                    reasonText.setText(curApplyBean.getReason());
                    //应为是修改之前的申请要带上之前请假条的ID
//       选项框回显选中有点复杂不搞了
//                    typeRG.check(lastRefuseApply.getType());
                    //获取完数据后UI操作
                    //主线程将alertDialog提示隐藏
                    Objects.requireNonNull(getActivity()).runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            alertDialog.hide();
                        }
                    });
                } catch (JSONException e) {
                    System.out.println(e);
                    Log.d(TAG, "获取数据成功");
                } catch (IOException e) {
                    System.out.println(e);
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {

            }
        });


        return null;
    }


// 处理审批销假的逻辑

    View shenheClearanceView;
    MyImageView jiankangmaImg_shenhe;
    MyImageView xingchengImg_shenhe;
    MyImageView heshuanImg_shenhe;
    Button jujueXiaojia;
    Button tonggiuoxiajia;
    AlertDialog dialog2;

    void shenhexiaojia() {

        initClaeranceDialogView();
//        打开审核销假对话框
//        没有需要审批的销假
        if(leaveClearance==null){
            return;
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
         dialog2 = builder.create();
        try {
            ((ViewGroup)shenheClearanceView.getParent()).removeView(shenheClearanceView);
        }
        catch (Exception e){
            System.out.println(e);
        }
        dialog2.setView(shenheClearanceView);
        dialog2.show();
        dialog2.getWindow().setLayout(1400, 2500);

    }

    /**
     * 初始化处理审核销假对话框
     */
    void initClaeranceDialogView() {
        shenheClearanceView = View.inflate(getContext(), R.layout.shenhe_clearance, null);
        jiankangmaImg_shenhe = shenheClearanceView.findViewById(R.id.jiankangmaImg_shenhe);
        xingchengImg_shenhe = shenheClearanceView.findViewById(R.id.xingchengImg_shenhe);
        heshuanImg_shenhe = shenheClearanceView.findViewById(R.id.heshuanImg_shenhe);
        tonggiuoxiajia = shenheClearanceView.findViewById(R.id.tongguo);
        jujueXiaojia = shenheClearanceView.findViewById(R.id.jujue);
        tonggiuoxiajia.setOnClickListener(mOnClickListener);
        jujueXiaojia.setOnClickListener(mOnClickListener);
        getClaeracne();
    }


    //查询出这个请假单的 销假最新的销假记录
    LeaveClearance leaveClearance;

    void getClaeracne() {
        //发送请求 获取当前点击的请假申请
        Call<ResponseBody> call = HttpUtil.getUserService().getLastwaitForApproverclearance(userNumber);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    String strBack = response.body().string();
                    //处理数据
                    JSONObject jsonObject = null;
                    jsonObject = new JSONObject(strBack);
                    Gson gson = new Gson();

                    leaveClearance = gson.fromJson(jsonObject.toString(), TempBean2.class).getData();
                    if (leaveClearance == null) {
                        return;
                    }
                    jiankangmaImg_shenhe.setImageURL(leaveClearance.getHealthCode());
                    heshuanImg_shenhe.setImageURL(leaveClearance.getNucleicAcidInfor());
                    xingchengImg_shenhe.setImageURL(leaveClearance.getStrokeCode());


                    //应为是修改之前的申请要带上之前请假条的ID

                    //获取完数据后UI操作
                    //主线程将alertDialog提示隐藏
                    Objects.requireNonNull(getActivity()).runOnUiThread(new Runnable() {
                        @Override
                        public void run() {


                        }
                    });
                } catch (JSONException e) {
                    System.out.println(e);
                    Log.d(TAG, "获取数据成功");
                } catch (IOException e) {
                    System.out.println(e);
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {

            }
        });
    }


}
